<template>
  <div>
    <el-card>
      <el-form :inline="true" :model="query" class="query-form" size="small">
        <el-form-item class="query-form-item">
          <el-input v-model="query.name" placeholder="请输入商家模板名称"
            prefix-icon="el-icon-search" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-refresh" @click="onRest"></el-button>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
          <el-button type="primary" icon="el-icon-edit" @click.native="handleForm('添加', null, null)">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="multipleTable" v-loading="listLoading" :data="list"
        :header-cell-style="{ background: '#F4F4F5', color: '#606266' }" border>
        <el-table-column label="商家模板 ID" prop="id" align="center"/>
        <el-table-column label="商家模板名称" prop="name" align="center"/>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click.native="handleForm('编辑', scope.$index, scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination-container"
        background
        :page-size="query.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :current-page="this.query.currentPage"
        :page-sizes="[5,10, 20, 30, 50]"
        :total="totalNumber"></el-pagination>
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
        :close-on-click-modal="false">
        <template slot="title">
          <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
              <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
              {{title}}
          </span>
          </div>
        </template>
        <el-card>
          <el-form :inline="true" :model="submitJson" ref="formRef" class="query-form" size="small">
            <el-form-item prop="name" :rules="{required: true, message: '模板名称不能为空', trigger: 'blur'}">
              <el-input v-model="submitJson.name" placeholder="请输入模板名称" clearable></el-input>
            </el-form-item>
            <div v-for="(item, index) in submitJson.templateItemFormList" :key="index">
              <el-form-item :rules="{required: true, message: '审核项名称不能为空', trigger: 'blur'}" :prop="'templateItemFormList.' + index + '.fieldname'">
                <el-input placeholder="输入审核项名称" v-model="item.fieldname"></el-input>
              </el-form-item>
              <el-form-item :rules="{required: true, message: '模板类型不能为空', trigger: 'change'}" :prop="'templateItemFormList.' + index + '.fieldtype'">
                <el-select style="width: 115px" v-model="item.fieldtype">
                  <el-option :label="'数字'" :value="'2'"></el-option>
                  <el-option :label="'文字'" :value="'0'"></el-option>
                  <el-option :label="'图片'" :value="'1'"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select style="width: 115px" v-model="item.ismust">
                  <el-option :label="'必填'" :value="0"></el-option>
                  <el-option :label="'非必填'" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="addProjectName(index)" class="setBtn" type="primary"
                  icon="el-icon-plus" plain size="mini"></el-button>
                <el-button @click="delProjectName(index)" class="setBtn" type="danger"
                  icon="el-icon-minus" plain size="mini"></el-button>
              </el-form-item>
            </div>
          </el-form>
        </el-card>
        <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submitTemplate">确 定</el-button>
      </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  import {
    getTemplateList,
    addOrEditTemplate
  } from "../../api/classification/classification.js";

  const templateFromList = {
    name: "", // 模板名称
    templateItemFormList: [
      // 模板数组
      {
        fieldname: "", // 模板名字
        fieldtype: null, // 模板类型
        fieldvalue: null, // 这个不用管
        ismust: 0 // 1必填 0非必填
      }
    ]
  };
  export default {
    data() {
      return {
        listLoading: false,
        submitJson: templateFromList, // 添加 编辑的数据
        title: "新增",
        dialogVisible: false, // 判断弹框是否显示
        list: [],
        query: {
          name: "",
          currentPage: 1,
          pageSize: 5,
          templateType: 1
        },
        totalNumber: 0,
        loading: false
      };
    },
    methods: {
      // 点击添加
      addProjectName(index) {
        this.submitJson.templateItemFormList.splice(index + 1, 0, {
          fieldname: "", // 模板名字
          fieldtype: null, // 模板类型
          fieldvalue: null, // 这个不用管
          ismust: 0 // 1必填 0非必填
        });
      },
      // 点击删除
      delProjectName(index) {
        if (this.submitJson.templateItemFormList.length > 1) {
          this.submitJson.templateItemFormList.splice(index, 1);
        }
      },
      // 确定提交模板
      submitTemplate() {
        // if (!this.submitJson.name) {
        //   this.$message.warning("模板名称不能为空");
        //   return
        // }
        // this.submitJson.templateItemFormList.forEach((el, index) => {
        //   if (!el.fieldname) {
        //     this.$message.warning("名称不能为空");
        //     throw new Error();
        //   }
        //   if (!el.fieldtype) {
        //     this.$message.warning("模板类型不能为空");
        //     throw new Error();
        //   }
        // });
        this.$refs['formRef'].validate((valid) => {
          if (valid) {
            let v = this.submitJson;
            let params = {
              templatetype: 1,
              name: v.name,
              templateItemFormList: v.templateItemFormList
            };
            if (this.title === "编辑") {
              params.id = v.id;
            }
            this.loading = true;
            addOrEditTemplate(params).then((res) => {
              if (res.code === 0) {
                this.$message.success("提交成功");
                this.dialogVisible = false;
                this.submitJson = templateFromList;
                this.getList();
                setTimeout(() => {
                  this.loading = false;
                }, 0.3 * 1000);
              } else {
                setTimeout(() => {
                  this.loading = false;
                }, 0.3 * 1000);
                this.$message.error(res.message);
              }
            })
              .catch((res) => {
                this.$message.error(res.message);
                this.loading = false;
              })

          }
        })
      },
      // 关闭弹框
      handleClose() {
        this.dialogVisible = false;
        this.$refs['formRef'].clearValidate()
      },
      onRest() {
        this.query = {
          username: "",
          status: "",
          currentPage: 1,
          pageSize: 10,
          templateType: 1,
          roleId: ""
        };
        this.getList();
      },
      // 搜索查询
      onSubmit() {
        this.query.currentPage = 1;
        this.getList();
      },
      // 新增 编辑
      handleForm(title, index, row) {

        this.title = title;
        if (title === "编辑") {
          // console.log(row)
          this.submitJson = JSON.parse(JSON.stringify(row));
        }else{
          this.submitJson = {
            name: "", // 模板名称
              templateItemFormList: [
            // 模板数组
            {
              fieldname: "", // 模板名字
              fieldtype: null, // 模板类型
              fieldvalue: null, // 这个不用管
              ismust: 0 // 1必填 0非必填
            }
          ]
          };
        }
        this.dialogVisible = true;
      },
      handleCurrentChange(val) {
        this.query.currentPage = val;
        //scrollTo(0, 800);
        this.getList();
      },
      handleSizeChange(val) {
        this.query.currentPage = 1;
        this.query.pageSize = val;
        this.getList();
      },
      async getList() {
        this.listLoading = true;
        let params = this.query;
        let res = await getTemplateList(params);
        if (res.code === 0) {
          this.list = res.data.list;
          this.totalNumber = res.data.totalNumber;
          this.listLoading = false;
        } else {
          this.$message.error(res.message);
        }
      }
    },
    created() {
      this.getList();
    }
  };
</script>

<style scoped>
  .head {
    display: flex;
    justify-content: flex-start;
  }

  .head p {
    min-width: 70px !important;
    line-height: 40px;
  }
</style>
